package com.coollang.smartbra.presenter;

import com.coollang.smartbra.fragment.SportStatisticsFragment;
import com.coollang.smartbra.model.SportRecordModel;
import com.coollang.smartbra.model.WeekActionModel;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

/**
 * @author: Timmy
 * @data: 2018/1/30
 * @Fuction:
 */

public class SportStatisticsFragmentPresenter {

    private SportStatisticsFragment mSportStatisticsFragment;
    private List<SportRecordModel.DataBean> mDataBeanList;


    public SportStatisticsFragmentPresenter(SportStatisticsFragment sportStatisticsFragment) {
        mSportStatisticsFragment = sportStatisticsFragment;
    }

    public void setData(List<SportRecordModel.DataBean> dataBeanList) {
        this.mDataBeanList = dataBeanList;
    }

    /**
     * 获取一周的时间
     */
    public List<WeekActionModel> getWeekData(List<SportRecordModel.DataBean> dataBeanList) {
        // 将mDataBeanList 拆成7天算
        List<WeekActionModel> weekList = new ArrayList<>();

        if (dataBeanList == null || dataBeanList.size() == 0) {
            return weekList;
        }

        SportRecordModel.DataBean firstData = dataBeanList.get(0);
        WeekActionModel weekBean = new WeekActionModel();
        int firstWeek = getWeekByDate(firstData.getDate(), "yyyy-MM-dd");
        weekBean.setFirstTimeStamp(firstData.getTimeStamp());
        int week = firstWeek;

        for (SportRecordModel.DataBean dataBean : dataBeanList) {
            // active: 避免出现第一条数据为星期一,然后直接添加进集合
            if (week == Calendar.MONDAY) {
                weekList.add(weekBean);
                weekBean = new WeekActionModel();
                // 添加这一周的第一天时间
                weekBean.setFirstTimeStamp(dataBean.getTimeStamp());
            }

            // 查看下一天是星期几
            week = week % 7 + 1;
            weekBean.setCount(weekBean.getCount() + dataBean.getCount());
            weekBean.setDuration(weekBean.getDuration() + dataBean.getDuration());
            weekBean.setHeartRate(weekBean.getHeartRate() + dataBean.getHeartRate());

            // 添加这一周的最后一天时间
            weekBean.setLastTimeStamp(dataBean.getTimeStamp());
        }


        weekList.add(weekBean);

        if (firstWeek == Calendar.MONDAY) {
            weekList.remove(0);
        }

        return weekList;
    }

    public static int getWeekByDate(String date, String myFm) {
        SimpleDateFormat fm = new SimpleDateFormat(myFm);
        Date mdate = null;
        try {
            mdate = fm.parse(date);
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(mdate);
            return calendar.get(Calendar.DAY_OF_WEEK);
        } catch (ParseException e) {
            e.printStackTrace();
        }

        return -1;
    }
}
